package org.monitor.config;

import java.net.URL;
import java.util.Properties;

public class MonitorConfig {

	public static final String RESOURCE = "/monitor.properties";
	
	public static final String STORE_DIR = "storedir";
	public static final String MAX_SIZE = "maxsize";
	public static final String OVER_RIDE = "override";
	public static final String SERVLET = "servlet";
	
	private static MonitorConfig instance = new MonitorConfig();
	
	private Properties prop;
	
	private String storeDir;
	private String tmpDir;
	private long maxSize = -1;
	private Boolean override;
	private String servlet;

	private MonitorConfig(){
		init();
	}
	
	public static MonitorConfig get() {
		return instance;
	}

	private void init(){
		prop = new Properties();
		try {
			URL url = MonitorConfig.class.getResource(RESOURCE);
			if(url != null){
				prop.load(url.openStream());
			}
		} catch (Exception e) {
		}
	}
	
	public String getProp(String name){
		String value = prop.getProperty(name);
		return value == null ? "" : value.trim();
	}
	
	/**
	 * 获取存储目录，默认为%WebRoot%/uploadFiles/
	 * @return
	 */
	public String getStoreDir(){
		if(this.storeDir == null){
			String value = getProp(STORE_DIR);
			if(value != null){
				if(value.startsWith("%WebRoot%")){
					storeDir = this.getClass().getClassLoader().getResource("/").getPath() + value.replace("%WebRoot%", "");
				}else {
					storeDir = value;
				}
			}else {
				storeDir = this.getClass().getClassLoader().getResource("/uploadFiles").getPath();
			}
		}
		return this.storeDir;
	}
	
	/**
	 * 获取临时目录，默认为java.io.tmpdir
	 * @return
	 */
	public String getTmpDir(){
		if(this.tmpDir == null){
			this.tmpDir = System.getProperty("java.io.tmpdir");
		}
		return tmpDir;
	}
	
	/**
	 * 获取上传文件最大值,单位为kb
	 * @return
	 */
	public long getMaxSize(){
		if(this.maxSize == -1){
			String value = getProp(MAX_SIZE);
			if("".equals(value)){
				maxSize = 0;
			}else {
				maxSize = Long.valueOf(value);
			}
			if(maxSize < 0){
				maxSize = 0;
			}
		}
		return maxSize;
	}
	
	/**
	 * 当文件名重复时是否覆盖，默认为false
	 * @return
	 */
	public boolean override(){
		if(override == null){
			String value = getProp(OVER_RIDE);
			override = Boolean.valueOf(value);
		}
		return override;
	}
	
	/**
	 * 获取服务器请求地址
	 * @return
	 */
	public String getServlet(){
		if(servlet == null){
			servlet = getProp(SERVLET);
		}
		return servlet;
	}
	
}
